'use strict';
const db = uniCloud.database();
const dbCmd = db.command
const $ = db.command.aggregate
const tools = require("../../tools/index.js")
const alioss = require('../../oss/index.js')
const Encryption_decryption = require('../../JSEncrypt/index.js')


// 获取文章列表接口
exports.SelArticleList = async (body_data)=>{
	let {pageNum,pageSize,
		Nickname,account,sex,IsCurrentUse,PublishBeginTime,PublishEndTime
	} = body_data
	if(!pageSize) return {code:200,msg:"参数错误~"}
	let Skips = pageNum * pageSize
	let res = {
		code:200,
		msg:"成功~"
	}
	
	/******	处理参数为空的数据 不传给数据库	******/  
	let MatchJson = {UserInfo:{}}
	let SelArg = ['Nickname','account','sex','IsCurrentUse'] // 匹配参数
	let like_SelArg = ['Nickname','account','sex'] // 需要模糊查询的参数(查询的条件在另外一个表)
	for(let i in SelArg){ 
		if(body_data[SelArg[i]]){
			MatchJson[SelArg[i]] = body_data[SelArg[i]]
			if(like_SelArg.findIndex(item=>item===SelArg[i])!==-1){ // 处理模糊查询
				MatchJson.UserInfo[SelArg[i]] = new RegExp(`${body_data[SelArg[i]]}`)
				delete MatchJson[SelArg[i]]
			}
		}
	}
	/*****	处理参数的日期查询范围	******/
	PublishBeginTime && PublishEndTime ?  MatchJson['PublishTime'] = dbCmd.and([
	  dbCmd.gte(new Date(PublishBeginTime)),
	  dbCmd.lte(new Date(PublishEndTime))
	]) :""
	
	try{
		const affair = await db.runTransaction(async transaction => {
			// 返回total
			let total = await transaction.collection('Article').aggregate().lookup({
				from:'User',
				localField:'UserId',
				foreignField:'_id',
				as:"UserInfo"
			}).unwind('$UserInfo').match(MatchJson).count('TOTAL').end()
			
			// 返回文章列表信息
			let result = await transaction.collection('Article').aggregate().sort({PublishTime:-1})
			.lookup({
				from:'User',
				localField:'UserId',
				foreignField:'_id',
				as:"UserInfo"
			}).lookup({
				from:'common',
				localField:'_id',
				foreignField:'articleId',
				as:"CommonList"
			}).unwind('$UserInfo')
			.match(MatchJson).skip(Skips).limit(pageSize).end()
			
			return {
				data:result.data,
				total:total.data.length>0?total.data[0].TOTAL:0
			}
		})
		return {
			code:200,
			msg:"查询成功~",
			total:affair.total,
			data:affair.data,
			MatchJson
		}
	}catch(e){
		console.error('事务报错：', e)
		return {
			code:500,
			msg:'内部错误~',
			error: e
		}
	}
}

// 更新文章发布信息
exports.UpdArticle = async (body_data)=>{
	let {contents,_id} = body_data
	if(!contents || !_id) return {code:200,msg:"参数错误~"}
	
	let res = {
		code:200,
		msg:"修改成功~"
	}
	let result = db.collection('Article').doc(_id).update({contents})
	res.data = result
	return res
}

// 删除文章发布信息
exports.DelArticle = async (body_data)=>{
	let {_id} = body_data
	if(!_id) return {code:200,msg:"参数错误~"}
	
	let res = {
		code:200,
		msg:"删除成功~"
	}
	let result = await db.collection('Article').where({_id}).get()
	if(result.data[0].imgList.length!==0) {
		let fileList = []
		result.data[0].imgList.forEach((i)=>{fileList.push(i.fileid)})
		let DelImgResult = await uniCloud.deleteFile({fileList});
		res.DelImgResult = DelImgResult
	}
	let DelData =  await db.collection('Article').doc(_id).remove()
	res.DelData = DelData
	return res
}

